<?php

namespace App\Admin\Controllers;

use App\Models\Category;
use App\Models\Product;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;

class ProductsController extends CommonProductsController
{
    public function getProductType()
    {
        return Product::TYPE_NORMAL;
    }

    public function customGrid(Grid $grid)
    {
        $grid->model()->with('category');
        $grid->id('ID')->sortable();
        $grid->title('商品名称');
        $grid->column('category.name', '类目');
        $grid->on_sale('已上架')->display(function ($value) {
            return $value ? '是' : '否';
        });
        $grid->price('价格');
        $grid->rating('评分');
        $grid->sold_count('销量');
        $grid->review_count('评论数');

        $grid->actions(function ($actions) {
            $actions->disableView();
            $actions->disableDelete();

            $id = $actions->getKey();
            $actions->append("<a href='activity/create/$id'><i class='fa fa-paper-plane' title='创建计划'></i></a>");
        });
    }

    public function customForm(Form $form)
    {

    }

    public function search(Request $request)
    {
        $q = (string)$request->input('q');
        $result = Product::where('title', 'like', "%$q%")
            ->where('type', Product::TYPE_NORMAL)
            ->where('on_sale', true)
            ->paginate(null, ['id', 'title']);
        $result->setCollection($result->getCollection()->map(function (Product $product) {
            return ['id' => $product->id, 'text' => $product->title];
        }));
        return $result;
    }
}
